<?php
/**
 * @name 合同Service
 * @Author : yu
 * @Created : 2016-11-1
 * @Copyright : MPE.Fiidee.Monda.Cn
 */
namespace trading\service;

use herosphp\bean\Beans;
use herosphp\core\Loader;

use models\TradingContractModel;
use models\TradingOrderModel;
use utils\x1\MyFunction;
use utils\x1\MyNumber;
use api\utils\SaasApiClient;

Loader::import('utils.x1.MyFunction');


class ContractService extends CommonService
{
    private $thisModel=null;

    public function __construct()
    {
        $this->thisModel=Loader::model('tradingContract');
        Loader::model('tradingOrder');
    }
    //合同搜索
    public function search($pagesize, $page, $search_arr)
    {

        $offset = $pagesize * ($page - 1); //计算记录偏移量

        $whereSql = "And contract.app_id='".appId()."'";

        //选择导出 add By Laoliu
        if( $search_arr['id'] ){
            $whereSql .= " AND contract.id in {$search_arr['id']}";
        }
        if ($search_arr['order_way'] != '' && $search_arr['order_way'] != 'all') {

            $whereSql .= " And o.pay_way=" . $search_arr['order_way'];
        }
        if ($search_arr['status'] != '' && $search_arr['status'] != 'all') {

            $whereSql .= " And contract.status=" . $search_arr['status'];
        }

        if ($search_arr['start_time'] != '' || $search_arr['end_time'] != '') {

            $whereSql .= " And " . MyFunction::betweenSqlByTime('unix_timestamp(contract.signed_time)', strtotime($search_arr['start_time']), strtotime($search_arr['end_time']));

        }
        if ($search_arr['member_id'] != '' && $search_arr['member_id'] != 'all') {

            $whereSql .= " And contract.buyers_member_id='" . $search_arr['member_id']."'";
        }

        if (in_array($search_arr['select_mix_option'], array('contract_no', 'order_no', 'buyers'))) {
            if ($search_arr['select_mix_option'] == 'order_no') {

                $whereSql .= " And o.{$search_arr['select_mix_option']} Like '%{$search_arr['select_mix_option_value']}%'";

            } else {

                $whereSql .= " And contract.{$search_arr['select_mix_option']} Like '%{$search_arr['select_mix_option_value']}%'";

            }
        }


        $count_sql = "Select  count(*)
                From trading_contract  As contract
                Left Join trading_order As o On contract.order_id=o.id Where 1 $whereSql";
        $total = $this->thisModel->getDB()->excute($count_sql)->fetchColumn();

        //分页查询
        $pageinationSql = isset ($offset) ? " Limit $offset,$pagesize" : " Limit 0,$pagesize";

        $sql = "Select contract.*,contract.id As contract_id,o.*
                From trading_contract  As contract
                Left Join trading_order As o On contract.order_id=o.id Where 1 $whereSql
                Order By contract.signed_time Desc $pageinationSql";

        $items = $this->thisModel->getDB()->excute($sql)->fetchAll($fetch_style = 2);

        return array("items" => $items, "total" => $total);
    }


    /**
     * 订单生成合同
     * @param $order_id 订单id
     * @param $member_id 订单用户id
     * @return int
     */
    public function addContract($order_id,$member_id,$time)
    {
        $memberService=Beans::get('member.member.service');

        $myNumber=new MyNumber(appId());
        $contract_no=$myNumber->build_no('ht');//生成合同号
        $progress = TradingContractModel::PROGRESS_CONTRACT_GREATE;

        $company=$memberService->getCompanyById($member_id);
        //获取卖家信息
        $sellersCompany=$memberService->getCompanyByAppId(appid(),'company,address,prov,city,dist');

        $sellersUser=$memberService->getUserByAppId(appid(),'virtual_account,sign_bank_branch');

        if(!$sellersCompany){
            $sellersCompany['company']='';
            $sellersCompany['address']='';
        }else{
            $ids[] = $sellersCompany['prov'];
            $ids[] = $sellersCompany['city'];
            $ids[] = $sellersCompany['dist'];
            $url = "api/area/getAreaByids";
            $result = SaasApiClient::send($url,array('ids'=>$ids));
            $area = '';
            if($result->isSucess()){
                $area = $result->getItem();
            }else{
                Log::error($result -> getMessage());
            }
            $sellersCompany['address'] = $area.$sellersCompany['address'];
        }
        if(!$sellersUser){
            $sellersUser['virtual_account']='';
            $sellersUser['sign_bank_branch']='';
        }
        $addData = array(
            "contract_no" => $contract_no,
            "sellers" => $sellersCompany['company'],
            "buyers" => $company['company'],
            "buyers_member_id" => $member_id,
            "signed_time" => myNow(),
            "status" => TradingContractModel::STATUS_NO_TRADING,//未成交
            "progress" => $progress,//合同生成
            "received_amount" => 0,
            "payment_amount" => 0,
            "received_quantity" => 0,
            "delivery_quantity" => 0,
            "order_id" => $order_id,
            "final_payment_time" => myNow(),
            "seller_address" => $sellersCompany['address'],
            "seller_phone" => C('contract_phone'),
            "seller_fax" => C('contract_fax'),
            "seller_sign_bank_branch" => $sellersUser['sign_bank_name'],
            "seller_virtual_account" => $sellersUser['virtual_account'],
        );
        return $this->thisModel->add($addData);
    }
    /**
     * 更新合同
     * @param $order_id 订单id
     * @param $member_id 订单会员id
     * @param $progress 合同进度
     * @param $data 需要更新的参数
     * @param $pay_way 支付方式
     * @return mixed
     */
    public function updateContract($order_id,$member_id,$progress,$data,$pay_way){

        //合同进度(0:合同生成,1:买方付款,2:卖方收款,3:卖方发货,4:买方收货验货)
        $updateData = array(
            "progress" => $progress,//合同进度
        );

        switch($progress){
            case TradingContractModel::PROGRESS_CONTRACT_GREATE://未付款可以更改合同
                $updateData['progress'] = TradingContractModel::PROGRESS_CONTRACT_GREATE;
                break;
            case TradingContractModel::PROGRESS_BUYER_MONEY_PAYED://买方付款
                $updateData['payment_amount'] = $data;//买家付款金额
                if($pay_way==TradingOrderModel::PAY_WAY_ONLINE){//线上支付  卖方不需要确认收款
                    $updateData['received_amount'] = $data;//卖家收款金额
                }
                break;
            case TradingContractModel::PROGRESS_SELLER_MONEY_COLLECTION:
                if($pay_way==TradingOrderModel::PAY_WAY_OFFLINE){//线下支付  卖方需要确认收款
                    $updateData['payment_amount'] = $data;//买家付款金额
                    $updateData['received_amount'] = $data;//卖家收款金额
                }
                break;
            case TradingContractModel::PROGRESS_SELLER_GOODS_DELIVERY:
                $updateData['delivery_quantity'] = $data;//发货数量
                break;
            case TradingContractModel::PROGRESS_BUYER_GOODS_RECEIPT:
                $updateData['received_quantity'] = $data;//收货数量
                $updateData['status'] = TradingContractModel::STATUS_IS_TRADING;//确认收货，完成交易。合同生效
                break;


        }
        return $this->thisModel->updates($updateData,array('order_id'=>$order_id,'buyers_member_id'=>$member_id));

    }


    /**
     * 合同状态
     * @param $k
     * @return mixed
     */
    public function getStatusText($k = '__all')
    {
        $arr = array('0' => '未成交', '1' => '已成交');
        return $k == '__all' ? $arr : $arr[$k];
    }

    /**
     * 合同进度
     * @param $k
     * @return mixed
     */
    public function getProgressText($k = '__all')
    {
        $arr = array('0' => '合同生成', '1' => '买方付款', '2' => '卖方收款', '3' => '卖方发货', '4' => '买方收货验货');
        return $k == '__all' ? $arr : $arr[$k];
    }
}

